package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Admin;
import org.csu.mypetstore.persistence.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    private String getEncryptedPassword(String salt, String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance( "MD5" );
        //将用户名作为盐拼接到密码后方
        String originText = password.concat( salt );
        md.update( originText.getBytes() );
        byte[] digest = md.digest();
        String hashText = DatatypeConverter.printHexBinary(digest).toUpperCase();

        return hashText;
    }

    public Admin login(String id, String pwd) throws NoSuchAlgorithmException {
        Admin admin = new Admin();
        admin.setId(id);
        admin.setPwd(getEncryptedPassword( id, pwd ));
        return adminMapper.getAdminByIdAndPwd(admin);
    }
}
